package com.example.qiandu.h264demo;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.Provider;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * Created by LQD ON 2018/5/29 0029
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener, ScreenCaputre.ScreenCaputreListener {

    public static MainActivity instance;
    private final static String TAG = MainActivity.class.getSimpleName();
    public ScreenCaputre screenCaputre;
    private static final int REQUEST_CODE = 1;
    public MediaProjectionManager mMediaProjectionManager;
    public MediaProjection mediaProjection;
    private OutputStream os;
    private Button startServerBtn,startRecordBtn,stopRecordBtn,closeAppBtn;
    private EditText ipEditText,portEditText;
    private TextView mInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance=this;
        startServerBtn=findViewById(R.id.startServerBtn);
        startRecordBtn=findViewById(R.id.startRecordBtn);
        stopRecordBtn=findViewById(R.id.stopRecordBtn);
        closeAppBtn=findViewById(R.id.closeAppBtn);

        startServerBtn.setOnClickListener(this::onClick);
        startRecordBtn.setOnClickListener(this::onClick);
        stopRecordBtn.setOnClickListener(this::onClick);
        closeAppBtn.setOnClickListener(this::onClick);

        ipEditText=findViewById(R.id.ip_EditText);
        portEditText=findViewById(R.id.port_EditText);

        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();

                if (!networkInterface.isLoopback() && !networkInterface.isVirtual()) {
                    // 遍历每个网络接口的IP地址列表
                    for (Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); addresses.hasMoreElements(); ) {
                        InetAddress address = addresses.nextElement();

                        // 判断是否为IPv4地址并且不是广播或多点传送地址
                        if (address instanceof Inet4Address && !address.isMulticastAddress() && !address.isLinkLocalAddress()) {
                            String ipAddress = address.getHostAddress();
                            ipEditText.setText(ipAddress);
                            Log.d("MainActivity", "IP Address: " + ipAddress);
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        mInfo = (TextView) findViewById(R.id.info);

    }


    private MyWebSocketServer myWebSocketServer;// = new MyWebSocketServer(16886);
    private WebSocket mWebSocket;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.startServerBtn:
                String ipStr=ipEditText.getText().toString();



                int port=0;
                try {
                    port=Integer.parseInt(portEditText.getText().toString());
                    InetSocketAddress inetSocketAddress=new InetSocketAddress(ipStr,port);
                    myWebSocketServer = new MyWebSocketServer(inetSocketAddress);
                    myWebSocketServer.start();
                } catch (Exception exception) {
                    Toast.makeText(this,"请输入正确的ip及端口号",Toast.LENGTH_SHORT).show();
                    setInfo("请输入正确的ip及端口号");
                    exception.printStackTrace();
                }

                break;
            case R.id.startRecordBtn:
                if (null == screenCaputre) {
                    prepareScreen();
                } else {
                    screenCaputre.start();
                }
                break;
            case R.id.stopRecordBtn:
                screenCaputre.stop();
                break;
            case R.id.closeAppBtn:
                finish();
                break;
        }
    }

    private class MyWebSocketServer extends WebSocketServer {

        public MyWebSocketServer(InetSocketAddress socketAddress) {
            
            super(socketAddress);
            Log.i(TAG, "MyWebSocketServer: ");
        }

        @Override
        public void start() {
            super.start();
            MainActivity.instance.setInfo("服务已启动");
            Log.i(TAG, "start: ");
        }

        @Override
        public void onOpen(WebSocket webSocket, ClientHandshake clientHandshake) {
            mWebSocket = webSocket;
            Log.v(TAG, "onOpen");
            setInfo("WebSocket  onOpen");

        }

        @Override
        public void onClose(WebSocket webSocket, int i, String s, boolean b) {
            Log.v(TAG, "onClose");
            setInfo("WebSocket  onClose");
        }

        @Override
        public void onMessage(WebSocket webSocket, String s) {
            Log.v(TAG, "onMessage");
            setInfo("WebSocket  onMessage: " + s);
        }

        @Override
        public void onError(WebSocket webSocket, Exception e) {
            Log.v(TAG, "onError");
            MainActivity.instance.setInfo("服务onError"+e);
            setInfo("WebSocket  onError: " + e);
        }
    }

    private Handler mHandler = new Handler();
    public void setInfo(final String message) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mInfo.setText(message);
            }
        });
    }
    public void prepareScreen() {
        mMediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mMediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "onActivityResult: "+requestCode);
        Log.i(TAG, "onActivityResult: "+resultCode);
        try {
            WindowManager mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics metrics = new DisplayMetrics();
            mWindowManager.getDefaultDisplay().getMetrics(metrics);
            Intent service = new Intent(MainActivity.instance, ScreenRecorder.class);
            service.putExtra("code", resultCode);
            service.putExtra("data", data);

            ComponentName componentName= startForegroundService(service);
            Log.d(TAG, "onActivityResult: "+componentName);

        } catch (Exception e){
            Log.e(TAG, "MediaProjection error",e);
        }




        /*DisplayMetrics dm = getResources().getDisplayMetrics();
        screenCaputre = new ScreenCaputre(dm.widthPixels, dm.heightPixels, mediaProjection);
        screenCaputre.setScreenCaputreListener(this);
        screenCaputre.start();*/
    }

    @Override
    public void onImageData(byte[] buf) {

        if (null != os) {
            try {
                byte[] bytes = new byte[buf.length + 4];
                byte[] head = intToBuffer(buf.length);
                System.arraycopy(head, 0, bytes, 0, head.length);
                System.arraycopy(buf, 0, bytes, head.length, buf.length);
                os.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (null != mWebSocket) {
            setInfo("发送H264数据成功，长度：" + buf.length);
            mWebSocket.send(buf);
        }
    }

    public static byte[] intToBuffer(int value) {
        byte[] src = new byte[4];
        src[3] = (byte) ((value>>24) & 0xFF);
        src[2] = (byte) ((value>>16) & 0xFF);
        src[1] = (byte) ((value>>8) & 0xFF);
        src[0] = (byte) (value & 0xFF);
        return src;
    }



}
